#include "jrtp_transmission.h"

jrtp_transmission::jrtp_transmission(QObject *parent) :
    QObject(parent)
{

}

void jrtp_transmission::init_rtplib(const char* ipstr,uint destport,uint lacalport)
{

    uint destip = inet_addr(ipstr);
    destip = ntohl(destip);

        RTPUDPv4TransmissionParams transparams;
        RTPSessionParams sessparams;
        sessparams.SetOwnTimestampUnit(1.0/1000.0);
        sessparams.SetAcceptOwnPackets(true);
        transparams.SetPortbase(lacalport);
        checkerror( sess.Create(sessparams,&transparams) );
        RTPIPv4Address addr(destip,destport);
        checkerror( sess.AddDestination(addr) );
}

void jrtp_transmission::send_rtp_data(QByteArray bytes)
{

    QByteArray buffer_bytes;
    do
    {
    buffer_bytes=bytes.left(1024);
    checkerror( sess.SendPacket(buffer_bytes.data(),buffer_bytes.size(),0,false,10));
    bytes.remove(0,1024);
    }while( !bytes.isEmpty());


}

void jrtp_transmission::recieve_rtp_data(QByteArray& bytes)
{
        sess.BeginDataAccess();
        if (sess.GotoFirstSourceWithData())
        {
            do
            {
                RTPPacket *pack;

                while ((pack = sess.GetNextPacket()) != NULL)
                {
                    //bytes+=QByteArray::fromRawData
                    bytes+=QByteArray
                 ((const char*)pack->GetPayloadData(),pack->GetPayloadLength());

                    sess.DeletePacket(pack);
                }
            } while (sess.GotoNextSourceWithData());
        }

        sess.EndDataAccess();

#ifndef RTP_SUPPORT_THREAD
        checkerror( sess.Poll());
#endif // RTP_SUPPORT_THREAD

       // RTPTime::Wait(RTPTime(1,0));
}

void jrtp_transmission::checkerror(int rtperr)
{
    if (rtperr < 0)
    {
        std::cout << "ERROR: " << RTPGetErrorString(rtperr) << std::endl;
        exit(-1);
    }
}
